<template>
  <div style="padding: 20px;width: 50%;margin: 0 auto;border-radius: 20px">
    <h2>个人中心</h2>
    <el-form
        ref="formRef"
        :model="userForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
    >
      <div style="display: flex;justify-content: center;margin-bottom: 20px">
        <el-avatar shape="square" :icon="UserFilled" size="large" />
      </div>
      <el-form-item label="账号" prop="username">
        <el-input disabled v-model="userForm.username" />
      </el-form-item>
      <el-form-item label="用户名" prop="name">
        <el-input v-model="userForm.name" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="userForm.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="旧密码" prop="password1">
        <el-input type="password" show-password v-model="userForm.password1" placeholder="请输入旧密码" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input type="password" show-password v-model="userForm.newPassword" placeholder="请输入新密码" />
      </el-form-item>
      <div style="display: flex;justify-content: center">
        <el-button type="primary" @click="saveUser">提交</el-button>
      </div>
    </el-form>
  </div>
</template>

<script lang="js" setup>
import {ref, reactive, getCurrentInstance} from "vue";
import {ElMessage} from "element-plus";
import {UserFilled} from "@element-plus/icons-vue";


const {proxy} = getCurrentInstance();
const rules = reactive({
  name:{ required: true, message: '请输入用户名', trigger: 'blur' },
  phone:{ required: true, message: '请输入手机号', trigger: 'blur' },
  password1:{ required: true, message: '请输入旧密码', trigger: 'blur' },
  newPassword:{ required: true, message: '请确认密码', trigger: 'blur' },
})
let userForm = reactive(JSON.parse(sessionStorage.getItem('user-data')));
// 文件上传成功时的钩子


const saveUser=()=> {
  proxy.$refs.formRef.validate((valid) => {
    if (valid) {
      if (userForm.password === userForm.password1) {
        userForm.password = userForm.newPassword;
        proxy.$request.put('/user/update', userForm).then(res => {
          if (res.code === '200') {
            // 更新成功
            ElMessage({message: '更新成功！', type: 'success'})
            // 清除缓存，跳转登录
            sessionStorage.removeItem('user-data');
            proxy.$router.push('/login');
          } else {
            ElMessage({message: res.msg, type: 'error'})
          }
        });
      } else {
        ElMessage({message: '旧密码错误！',type: "error"});
      }
    }
  });
}

</script>
<style scoped>

</style>